package com.ct.commons.run;

import com.ct.commons.annotation.PermissionApi;
import com.ct.rbac.orm.SysApisDO;
import com.ct.rbac.repository.ISysApisRespontory;
import com.ct.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class RbacAutoSaveLineRunner implements CommandLineRunner {

    @Autowired
    private ISysApisRespontory sysApisRespontory;

    @Override
    public void run(String... args) throws Exception {
        String packageName = "com.ct.controller";
        List<String> clazzName = ClazzUtils.getClazzName(packageName, true);
        for (String s : clazzName) {
            Class<?> aClass = Class.forName(s);
            PermissionApi pannotation = aClass.getAnnotation(PermissionApi.class);
            if (Objects.nonNull(pannotation)){
                SysApisDO sysApisDO = transferSysApiDo(pannotation, 0L);
                boolean b = sysApisRespontory.saveOrUpdate(sysApisDO);
                if(b){
                    Long parentId = sysApisDO.getId();
                    Method[] methods = aClass.getMethods();
                    if(Objects.nonNull(methods) && methods.length > 0){
                        for (Method method : methods) {
                            PermissionApi cannotation = method.getAnnotation(PermissionApi.class);
                            if(Objects.nonNull(cannotation)) {
                                SysApisDO childrenDo = transferSysApiDo(cannotation, parentId);
                                sysApisRespontory.saveOrUpdate(childrenDo);
                            }
                        }
                    }
                }
            }

        }
    }

    private SysApisDO transferSysApiDo(PermissionApi permissionApi, Long parentId) {
        SysApisDO sysApisDO = sysApisRespontory.getSysApisDOByCode(permissionApi.code());
        if (sysApisDO == null) {
            sysApisDO = new SysApisDO();
        }
        sysApisDO.setTitle(permissionApi.title());
        sysApisDO.setPath(permissionApi.path());
        sysApisDO.setSorted(permissionApi.sorted());
        sysApisDO.setCode(permissionApi.code());
        sysApisDO.setMethod(permissionApi.method());
        sysApisDO.setStatus(1);
        sysApisDO.setParentId(parentId);
        return sysApisDO;
    }
}
